package com.demo.java.concurrent.thread;

import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
public class GuardedSuspensionBoxTest {
    public static void main(String[] args) throws InterruptedException {
        MailBox mailBox = new MailBox();
        for (int i = 1; i <= 3; i++) {
            new Thread(() -> {
                String obj = mailBox.createGuardedObject().get();
                log.info("get obj: " + obj);
            }, "get-thread" + i).start();
        }
        mailBox.ids().forEach(id -> {
            new Thread(() -> {
                try {
                    Thread.sleep(id * 1000 * 2);
                } catch (InterruptedException e) {}
                mailBox.post(id, "mail" + id);
            }, "send-thread" + id).start();
        });

        Thread.sleep(20000);
    }

    static class MailBox {
        private Map<Integer, GuardedObject<String>> mailMap = new ConcurrentHashMap<>();
        private AtomicInteger id = new AtomicInteger(0);
        public int generateId() {
            return id.incrementAndGet();
        }
        public void post(int id, String content) {
            mailMap.get(id).complete(content);
        }
        public GuardedObject<String> createGuardedObject() {
            GuardedObject<String> go = new GuardedObject<>();
            mailMap.put(generateId(), go);
            return go;
        }
        public Set<Integer> ids() {
            return mailMap.keySet();
        }
    }
}
